//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================
/*-------------------------------------------------------------------------
 * Filename:      xmodem.c
 * Version:       $Id: xmodem.c,v 1.1.2.1 2006/10/10 10:30:47 zhangyi Exp $
 * Copyright:     Copyright (C) 2001, Hewlett-Packard Company
 * Author:        Christopher Hoover <ch@hpl.hp.com>
 * Description:   xmodem functionality for uploading of kernels 
 *                and the like
 * Created at:    Thu Dec 20 01:58:08 PST 2001
 *-----------------------------------------------------------------------*/
/*
 * xmodem.c: xmodem functionality for uploading of kernels and 
 *            the like
 *
 * Copyright (C) 2001 Hewlett-Packard Laboratories
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

#ident "$Id: xmodem.c,v 1.1.2.1 2006/10/10 10:30:47 zhangyi Exp $"

#include "config.h"
#include "serial.h"
#include "util.h"
#include "crc16.h"

#define SOH 0x01
#define STX 0x02
#define EOT 0x04
#define ACK 0x06
#define NAK 0x15
#define CAN 0x18
#define BS  0x08
#define CTRLZ 0x1A

#define DLY_1S 1000
#define MAXRETRANS 10
/*

Cf:

  http://www.textfiles.com/apple/xmodem
  http://www.phys.washington.edu/~belonis/xmodem/docxmodem.txt
  http://www.phys.washington.edu/~belonis/xmodem/docymodem.txt
  http://www.phys.washington.edu/~belonis/xmodem/modmprot.col

*/

#define TIMEOUT 10
#define MAXERRORS 10

#define ERROR(...) do { } while (0)

static char blockBuf[1024];

static inline void ReadFlush()
{
    SerialInputFlush();
}

unsigned char _inbyte(unsigned int timeout)
{
    char buf[1];
    int n;

    n = SerialInputBlock_msec(buf, 1, timeout);

    if (n == 1)
        return buf[0] & 0xff;
    else
        return -1;
}

void _outbyte(unsigned char ch)
{
    SerialOutputRawByte(ch);
}

static void flushinput(void)
{
    SerialInputFlush();
}

int ReadByteWithTimeout(unsigned int timeout)
{
    char buf[1];
    int n;

    n = SerialInputBlock(buf, 1, timeout);

    if (n == 1)
        return buf[0] & 0xff;
    else
        return -1;
}

#if 0 /* NK9 */
int XModemReceive(char *bufBase, int bufLen)
#else
int XModemReceive(char *bufBase)
#endif
{
    unsigned int errors = 0;
    unsigned int wantBlockNo = 1;
    unsigned int length = 0;
    int crc = 1;
    char nak = 'C';

    ReadFlush();

    /* Ask for CRC; if we get errors, we will go with checksum */
    SerialOutputRawByte(nak);

    for (;;) {
        int blockBegin;
        int blockNo;
        int blockNoOnesCompl;
        int cksum = 0;
        int crcHi = 0;
        int crcLo = 0;
        int blockLength;

        blockBegin = ReadByteWithTimeout( TIMEOUT );
        if (blockBegin < 0)
            goto timeout;

        nak = NAK;

        switch (blockBegin) {
        case SOH:
        case STX:
            break;

        case EOT:
            SerialOutputRawByte(ACK);
            goto done;

        default:
            goto error;
        }

        /* block no */
        blockNo = ReadByteWithTimeout( TIMEOUT );
        if (blockNo < 0)
            goto timeout;

        /* block no one's compliment */
        blockNoOnesCompl = ReadByteWithTimeout( TIMEOUT );
        if (blockNoOnesCompl < 0)
            goto timeout;

        if (blockNo != (255 - blockNoOnesCompl)) {
            SerialOutputString("bad block ones compl\n");
            goto error;
        }

        blockLength = (blockBegin == SOH) ? 128 : 1024;

        {
            int i;

            for (i = 0; i < blockLength; i++) {
                /* simon */
                /* unsigned char cc; */
                int cc;
//    signed char cc;
                cc = ReadByteWithTimeout( TIMEOUT );
                if (cc < 0)
                    goto timeout;
                blockBuf[i] = cc;
            }
        }

        if (crc) {
            crcHi = ReadByteWithTimeout( TIMEOUT );
            if (crcHi < 0)
                goto timeout;

            crcLo = ReadByteWithTimeout( TIMEOUT );
            if (crcLo < 0)
                goto timeout;
        } else {
            cksum = ReadByteWithTimeout( TIMEOUT );
            if (cksum < 0)
                goto timeout;
        }

        if (blockNo == ((wantBlockNo - 1) & 0xff)) {
            /* a repeat of the last block is ok, just ignore it. */
            /* this also ignores the initial block 0 which is */
            /* meta data. */
            goto next;
        } else if (blockNo != (wantBlockNo & 0xff)) {
            SerialOutputString("unexpected block no, ");
            SerialOutputHex(blockNo); SerialOutputString(", expecting ");
            SerialOutputHex(wantBlockNo); SerialOutputByte('\n');
            goto error;
        }

        if (crc) {
            int crc = 0;
            int i, j;
            int expectedCrcHi;
            int expectedCrcLo;

            for (i = 0; i < blockLength; i++) {
                crc = crc ^ (int) blockBuf[i] << 8;
                for (j = 0; j < 8; j++)
                    if (crc & 0x8000)
                        crc = crc << 1 ^ 0x1021;
                    else
                        crc = crc << 1;
            }

            expectedCrcHi = (crc >> 8) & 0xff;
            expectedCrcLo = crc & 0xff;

            if ((crcHi != expectedCrcHi) ||
                (crcLo != expectedCrcLo)) {
                SerialOutputString("crc error, expected ");
                SerialOutputHex(expectedCrcHi); SerialOutputByte(' ');
                       SerialOutputHex(expectedCrcLo); SerialOutputString(", got ");
                SerialOutputHex(crcHi); SerialOutputHex(crcLo); SerialOutputByte('\n');
                goto error;
            }
        } else {
            unsigned char expectedCksum = 0;
            int i;

            for (i = 0; i < blockLength; i++)
                expectedCksum += blockBuf[i];

            if (cksum != expectedCksum) {
                SerialOutputString("checksum error, expected ");
                SerialOutputHex(expectedCksum);  SerialOutputString(", got ");
                SerialOutputHex(cksum); SerialOutputByte('\n');
                goto error;
            }
        }

        wantBlockNo++;
        length += blockLength;

#if 0
        if (length > bufLen) {
            SerialOutputString("out of space\n");
            goto error;
        }
#endif

        {
            int i;
            for (i = 0; i < blockLength; i++)
                *bufBase++ = blockBuf[i];
        }

    next:
        errors = 0;
        SerialOutputRawByte(ACK);
        continue;

    error:
    timeout:
        errors++;
        if (errors == MAXERRORS) {
            /* Abort */
            int i;

            // if using crc, try again w/o crc
            if (nak == 'C') {
                nak = NAK;
                errors = 0;
                crc = 0;
                goto timeout;
            }

            SerialOutputString("too many errors; giving up\n");
            for (i = 0; i < 5; i ++)
                SerialOutputRawByte(CAN);
            for (i = 0; i < 5; i ++)
                SerialOutputRawByte(BS);
            return -1;
        }

        ReadFlush();
        SerialOutputRawByte(nak);
    }

 done:
    return length;
}

int xmodemTransmit(unsigned char *src, int srcsz)
{
    unsigned char xbuff[1030]; /* 1024 for XModem 1k + 3 head chars + 2 crc + nul */
    int bufsz, crc = -1;
    unsigned char packetno = 1;
    int i, c, len = 0;
    int retry;

    for(;;) {
        for( retry = 0; retry < 16; ++retry) {
            if ((c = _inbyte((DLY_1S)<<1)) >= 0) {
                switch (c) {
                case 'C':
                    crc = 1;
                    goto start_trans;
                case NAK:
                    crc = 0;
                    goto start_trans;
                case CAN:
                    if ((c = _inbyte(DLY_1S)) == CAN) {
                        _outbyte(ACK);
                        flushinput();
                        return -1; /* canceled by remote */
                    }
                    break;
                default:
                    break;
                }
            }
        }
        _outbyte(CAN);
        _outbyte(CAN);
        _outbyte(CAN);
        flushinput();
        return -2; /* no sync */

        for(;;) {
start_trans:
            xbuff[0] = SOH; bufsz = 128;
            xbuff[1] = packetno;
            xbuff[2] = ~packetno;
            c = srcsz - len;
            if (c > bufsz) c = bufsz;
            if (c >= 0) {
#if 0
                memset (&xbuff[3], 0, bufsz);
#else
                MyMemSetChar(&xbuff[3], 0, bufsz);
#endif
                if (c == 0) {
                    xbuff[3] = CTRLZ;
                }
                else {
#if 0
                    memcpy (&xbuff[3], &src[len], c);
#else
                    MyMemCpyChar(&xbuff[3], &src[len], c);
#endif
                    if (c < bufsz) xbuff[3+c] = CTRLZ;
                }
                if (crc) {
                    unsigned short ccrc = crc16_ccitt(&xbuff[3], bufsz);
                    xbuff[bufsz+3] = (ccrc>>8) & 0xFF;
                    xbuff[bufsz+4] = ccrc & 0xFF;
                }
                else {
                    unsigned char ccks = 0;
                    for (i = 3; i < bufsz+3; ++i) {
                        ccks += xbuff[i];
                    }
                    xbuff[bufsz+3] = ccks;
                }
                for (retry = 0; retry < MAXRETRANS; ++retry) {
                    for (i = 0; i < bufsz+4+(crc?1:0); ++i) {
                        _outbyte(xbuff[i]);
                    }
                    if ((c = _inbyte(DLY_1S)) >= 0 ) {
                        switch (c) {
                        case ACK:
                            ++packetno;
                            len += bufsz;
                            goto start_trans;
                        case CAN:
                            if ((c = _inbyte(DLY_1S)) == CAN) {
                                _outbyte(ACK);
                                flushinput();
                                return -1; /* canceled by remote */
                            }
                            break;
                        case NAK:
                        default:
                            break;
                        }
                    }
                }
                _outbyte(CAN);
                _outbyte(CAN);
                _outbyte(CAN);
                flushinput();
                return -4; /* xmit error */
            }
            else {
                for (retry = 0; retry < 10; ++retry) {
                    _outbyte(EOT);
                    if ((c = _inbyte((DLY_1S)<<1)) == ACK) break;
                }
                flushinput();
                return (c == ACK)?len:-5;
            }
        }
    }
}
